Sorts an array using Binarysearch method
C# .NET |
public static String DoTest() { String strRet = ""; // Creates and initializes a new Array. Array myIntArray = Array.CreateInstance( typeof(Int32), 5 ); for ( int i = myIntArray.GetLowerBound(0); i <= myIntArray.GetUpperBound(0); i++ ) myIntArray.SetValue( i*2, i ); // Displays the values of the Array. strRet += "The Int32 array contains the following:\r\n"; strRet += PrintValues( myIntArray ); // Locates a specific object that does not exist in the Array. int myObjectOdd = 3; strRet += FindMyObject(myIntArray, myObjectOdd ); // Locates an object that exists in the Array. Int32 myObjectEven = 6; strRet += FindMyObject(myIntArray, myObjectEven ); return strRet; } public static String PrintValues(Array myArr) { String strAll = ""; foreach(Int32 n in myArr) { strAll += (n.ToString() + "\t"); } strAll += "\r\n"; return strAll; } public static string FindMyObject(Array myArr, Object myObject ) { int myIndex=Array.BinarySearch( myArr, myObject ); string strRet = ""; if ( myIndex < 0 ) strRet = string.Format("The object to search for ({0}) is not found. The next larger object is at index {1}.", myObject, ~myIndex); else strRet = string.Format("The object to search for ({0}) is at index {1}.", myObject, myIndex ); return strRet; } |
Blaze++ .NET |
static String DoTest() { String strRet = ""; // Creates and initializes a new Array. Array myIntArray = Array::CreateInstance( typeof(Int32), 5 ); for ( int i = myIntArray.GetLowerBound(0); i <= myIntArray.GetUpperBound(0); i++ ) myIntArray.SetValue( i*2, i ); // Displays the values of the Array. strRet += "The Int32 array contains the following:\r\n"; strRet += PrintValues(myIntArray ); // Locates a specific object that does not exist in the Array. Int32 myObjectOdd = 3; strRet += FindMyObject(myIntArray, myObjectOdd ); // Locates an object that exists in the Array. Int32 myObjectEven = 6; strRet += FindMyObject(myIntArray, myObjectEven ); return strRet; } static String PrintValues(Array& myArr) { String strAll = ""; foreach(Int32, n, myArr) { strAll += (n.ToString() + "\t"); } strAll += "\r\n"; return strAll; } static String FindMyObject(Array& myArr, Object& myObject ) { Int32 myIndex=Array::BinarySearch( myArr, myObject ); String strRet = ""; if ( myIndex < 0 ) strRet = String::Format("The object to search for ({0}) is not found. The next larger object is at index {1}.", myObject, (Int32)~myIndex); else strRet = String::Format("The object to search for ({0}) is at index {1}.", myObject, myIndex ); return strRet; } |